﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Data.SqlClient;
using GMS.MainClasses;
using GMS.Dinasty.ReferenceGoods;
using GMS.MainForm;
//using RPV.Data;
using GMS.ServiceFunctions.FunctionForControls;
using GMS.ServiceFunctions.Data;


namespace GMS.Dinasty.Specifications
{
    public partial class Specifications : ChildForms
    {
        TreeNode SelectedNode = new TreeNode();
        FunctionForTreeView FFTV = new FunctionForTreeView();
        BindingSource mbs = new BindingSource();
        DataSet DS = new DataSet();
        DataTable DT = new DataTable();
        ReturnData RD = new ReturnData();
        BindingSource bsCustomer = new BindingSource();
      

        public String CaptionGood
        { set { dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value = value; } }
        public Int32 IdGood
        { set { dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Tag = value; } }
        public Specifications()
        {
            InitializeComponent();

            ConnectionString = "server=pavel;uid=pavel;pwd=123456;database=GMSDatabase";

            StoredProcedures = new String[9];
            StoredProcedures[0] = "DInsertSpecificationTemplate";
            StoredProcedures[1] = "DDeleteSpecificationsTemplate";
            StoredProcedures[2] = "DSelectSpecificationsTemplate";
            StoredProcedures[3] = "DSelectSpecificationstemplateContent";
            StoredProcedures[4] = "DInsertSpecificationsTemplates";
            StoredProcedures[5] = "DInsertTemplateSpecificationItem";
            StoredProcedures[6] = "DDeleteSpecificationTemplateWithItems";
            StoredProcedures[7] = "DSelectCustomers";
            StoredProcedures[8] = "DEditCustomer";
        }
        private void SelectTemplateSpecification()
        {


            //mbs.DataSource = MRF.ReturnDataSetDB(ConnectionString, StoredProcedures[2]);
            toolStripComboBox1.ComboBox.DataSource = RD.ReturnDataSetDB(ConnectionString, StoredProcedures[2]).Tables[0];
            toolStripComboBox1.ComboBox.DisplayMember = "Captiontemplate";
            toolStripComboBox1.ComboBox.ValueMember = "IdCaption";
        }
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
           /* if (e.KeyCode == Keys.F1 && this.dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name.ToString() == "Caption")
            {

                GMS.Dinasty.ReferenceGoods.ReferenceGoods CF = new GMS.Dinasty.ReferenceGoods.ReferenceGoods(this);
                //CF.ConnectionString = ConnectionString;
                CF.ConnectionString="server=pavel;uid=pavel;pwd=123456;database=GMSDatabase";
                
                CF.MdiParent = this.MdiParent;
                CF.Show();
                dataGridView1.CurrentCell = dataGridView1.CurrentRow.Cells[2];
            }*/
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            using (SolidBrush brush = new SolidBrush(((DataGridView)sender).RowHeadersDefaultCellStyle.ForeColor))
            {
                e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), e.InheritedRowStyle.Font, brush, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 3);
            }

        }
        /// <summary>
        /// CH2
        /// формирование блока способствующего перемещению курсора не на поле цена а на поле цена сос кидкой
        /// </summary>
        /// <param name="i"></param>
        delegate void SetColumnIndex(int i);
        private void Mymethod(int columnIndex)
        {
            this.dataGridView1.CurrentCell = this.dataGridView1.CurrentRow.Cells["LowPrice"];
        }

        private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Name.ToString() == "Quantity")
            {
                if (dataGridView1.CurrentCell.ColumnIndex != (dataGridView1.Columns.Count - 1))
                {
                    Int32 nextindex = Math.Min((dataGridView1.Columns.Count - 1), (dataGridView1.CurrentCell.ColumnIndex + 1));
                    SetColumnIndex method = new SetColumnIndex(Mymethod);
                    this.dataGridView1.BeginInvoke(method, nextindex);
                }
            }

        }
        /// окончание CH2
        private void Specifications_Activated(object sender, EventArgs e)
        {
            dataGridView1.Select();
        }
        private void Specifications_Load(object sender, EventArgs e)
        {
            SelectTemplateSpecification();
            RefreshTreeView();
        }
        private void applytemplateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (toolStripComboBox1.ComboBox.SelectedValue != null)
            {
                DT = RD.ReturnDataSetDB(ConnectionString, StoredProcedures[3] + " " + toolStripComboBox1.ComboBox.SelectedValue.ToString()).Tables[0];

                dataGridView1.DataSource = DT;
            }
            else
                MessageBox.Show("Не выбран шаблон!!!", "Ошибка выбора", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void toolStripTextBox1_KeyUp(object sender, KeyEventArgs e)
        {
            /// <summary>
            /// CH3
            /// формирование скики а так же провреки связанные со скидкой, проверка на допустимые значения
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            if (toolStripTextBox1.Text.Length>0 && Char.IsDigit(toolStripTextBox1.Text, toolStripTextBox1.Text.Length - 1))
            {
                if (dataGridView1.SelectedRows != null)
                {
                    foreach (DataGridViewRow DGWR in dataGridView1.SelectedRows)
                    {
                        if (DGWR.Cells["Price"].Value == null || DGWR.Cells["Price"].Value.ToString().Length == 0)
                            DGWR.Cells["LowPrice"].Value = 0;
                        else
                            DGWR.Cells["LowPrice"].Value = Convert.ToDecimal(DGWR.Cells["Price"].Value.ToString().Replace('.', ',')) - Convert.ToDecimal(DGWR.Cells["Price"].Value.ToString().Replace('.', ',')) / 100 * Convert.ToDecimal(toolStripTextBox1.Text);
                    }
                }
            }
            ///окончание CH3
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            /// <summary>
            /// CH1
            /// блок кода отвечающий за проверку введенных значений в поля - количество, цена, цена со скидкой
            /// проверка на больше меньше относительно цены и цены со скидкой
            /// установка формата выводимых данных в поля - количество, цена, цена со скидкой
            /// находим произведение кол-ва на цену со скидкой
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            if (dataGridView1.CurrentCell != null)
            {
                Decimal Q = 0, LP = 0, P = 0;
                if (this.dataGridView1.Columns[e.ColumnIndex].Name.ToString() == "Quantity" || this.dataGridView1.Columns[e.ColumnIndex].Name.ToString() == "LowPrice" || this.dataGridView1.Columns[e.ColumnIndex].Name.ToString() == "Price")
                {
                    if (dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value != null)
                    {
                        if (Decimal.TryParse(dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value.ToString().Replace('.', ','), out Q))
                            dataGridView1.Rows[e.RowIndex].Cells["Quantity"].Value = Q.ToString("#0.000");
                        else
                            Q = 0;
                    }
                    if (dataGridView1.Rows[e.RowIndex].Cells["LowPrice"].Value != null)
                    {
                        if (Decimal.TryParse(dataGridView1.Rows[e.RowIndex].Cells["LowPrice"].Value.ToString().Replace('.', ','), out LP))
                            dataGridView1.Rows[e.RowIndex].Cells["LowPrice"].Value = LP.ToString("#0.00");
                        else
                            LP = 0;
                    }

                    if (dataGridView1.Rows[e.RowIndex].Cells["Price"].Value != null)
                    {
                        if (Decimal.TryParse(dataGridView1.Rows[e.RowIndex].Cells["Price"].Value.ToString().Replace('.', ','), out P))
                            dataGridView1.Rows[e.RowIndex].Cells["Price"].Value = P.ToString("#0.00");
                        else
                            P = 0;
                    }

                    dataGridView1.Rows[e.RowIndex].Cells["Summ"].Value = (Q * LP).ToString("#0.00");



                    if (P < LP)
                    {
                        dataGridView1.Rows[e.RowIndex].ErrorText = "Цена со скидкой больше чем цена без скидки!!!";
                    }
                    else
                    {
                        dataGridView1.Rows[e.RowIndex].ErrorText = String.Empty;
                    }
                    Decimal summ = 0, lowsumm = 0;
                    foreach(DataGridViewRow DGWR in dataGridView1.Rows)
                    {
                        if (DGWR.Cells["Price"].Value == null || Decimal.TryParse(DGWR.Cells["Price"].Value.ToString().Replace('.', ','), out P)== false)
                            P = 0;

                        if (DGWR.Cells["Quantity"].Value == null || Decimal.TryParse(DGWR.Cells["Quantity"].Value.ToString().Replace('.', ','), out Q) == false)
                            Q = 0;

                        if (DGWR.Cells["LowPrice"].Value == null || Decimal.TryParse(DGWR.Cells["LowPrice"].Value.ToString().Replace('.', ','), out LP) == false)
                            LP = 0;
                        summ = summ + P * Q;
                        lowsumm = lowsumm + LP * Q;
                    }

                    label1.Text = "Сумма заказа - " + summ.ToString("N2")+" грн.";
                    label2.Text = "К оплате - " + lowsumm.ToString("N2")+ " грн.";
                    label3.Text = "Скидка - " + (summ - lowsumm).ToString("N2")+ " грн.";
                    ///окончание CH1

                }
            }
        }

        private void insertrowToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow.Index != dataGridView1.Rows.Count-1)
            {
                DataRow dr = DT.NewRow();
                DT.Rows.InsertAt(dr, dataGridView1.CurrentRow.Index + 1);
            }
        }

        private void AddToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DT.Rows.Count != 0)
            {
                DataTable Dt = RD.ReturnDataSetDB(ConnectionString, StoredProcedures[3] + " " + toolStripComboBox1.ComboBox.SelectedValue.ToString()).Tables[0].Copy();
                DataRow dr;
                Int32 g = dataGridView1.RowCount;
                Int32 f = dataGridView1.CurrentRow.Index;
                if (g == f+1)
                    f = f - 1;
                for (Int32 j = 0; j < Dt.Rows.Count; j++)
                {
                    dr = Dt.Rows[j];
                    DT.Rows.InsertAt(DT.NewRow(), f + j + 1);
                    DT.Rows[f + j + 1].ItemArray = Dt.Rows[j].ItemArray;
                }
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SqlConnection SC = new SqlConnection(ConnectionString);
            SC.Open();

            Int32 i;
            i =Convert.ToInt32(RD.ReturnDataSetDB(ConnectionString, StoredProcedures[4] + " " + toolStripComboBox1.Text.Trim()).Tables[0].Rows[0][0].ToString());

            SqlTransaction ST = SC.BeginTransaction();
            try
            {
                foreach (DataRow DR in DT.Rows)
                {
                    SqlCommand SCC = new SqlCommand(StoredProcedures[5] + " " + i.ToString() + ", " + DR[0].ToString(),SC);
                    SCC.Transaction = ST;
                    SCC.ExecuteNonQuery();
                    ST.Commit();
                }
            }
            catch(SqlException SQLE)
            {
                ST.Rollback();
                MessageBox.Show(SQLE.Message.ToString(), "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            SC.Close();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Удаление шаблона и всего его содержимого. Вы уверены?", "Предупреждение!!!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                SqlConnection SC = new SqlConnection(ConnectionString);
                SC.Open();
                SqlTransaction ST = SC.BeginTransaction();
                try
                {
                    SqlCommand SCC = new SqlCommand(StoredProcedures[6] + " " + toolStripComboBox1.ComboBox.SelectedValue.ToString(), SC);
                    SCC.Transaction = ST;
                    SCC.ExecuteNonQuery();
                    ST.Commit();
                }
                //catch(SqlException SQLE)
                catch
                {
                    ST.Rollback();
                    //MessageBox.Show(SQLE.Message.ToString(), "Ошибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                SC.Close();
                SelectTemplateSpecification();
            }
        }
        private void RefreshTreeView()
        {
            bsCustomer.DataSource = RD.ReturnDataSetDB(ConnectionString, StoredProcedures[7]);//bsMenu.DataSource = MRF.ReturnDataSetDB(ConnectionString, StoredProcedures[0]);

            bsCustomer.DataMember = "table";
            FFTV.FillTreeView(treeView1, bsCustomer, "IdUser", "IdParentUser", "CaptionUser");
            SelectedNode.Expand();
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            tabControl1.SelectedTab = tabPage2;
        }

        private void treeView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Move;
        }

        private void treeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void treeView1_DragDrop(object sender, DragEventArgs e)
        {
            TreeNode NewNode;

            if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
            {
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));

                TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);
                NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");

                if (DestinationNode.Level > NewNode.Level || DestinationNode == NewNode)
                {
                    MessageBox.Show("Недопустимая попытка перенести элемент!!!");
                }
                else
                {
                    DestinationNode.Nodes.Add((TreeNode)NewNode.Clone());

                    bsCustomer.Filter = "[IdUser] = " + NewNode.Tag;
                    /*Int32 i;
                    try
                    {
                        i = Convert.ToInt32(((DataRowView)bsCustomer.List[0])["IdForm"].ToString());
                    }
                    catch
                    {
                        i = 3;
                    }*/


                    //MRF.ExecuteSqlCommand(StoredProcedures[8] + " " + NewNode.Tag + "," + DestinationNode.Tag + ",'" + NewNode.Text + "',''", ConnectionString);
                    RD.ExecuteSqlCommand(StoredProcedures[8] + " " + NewNode.Tag + "," + DestinationNode.Tag + ",'" + NewNode.Text + "'", ConnectionString);
                    
                    DestinationNode.Expand();
                    //Remove Original Node
                    NewNode.Remove();
                }
            }
        }
    }
}
